#coding:utf-8

from PIL import Image
from queue import Queue


# 打开图片,convert图像类型有L,RGBA
img = Image.open('1.jpg').convert('L')
img = img.transpose(Image.ROTATE_90)
#img.show();print(img.size[0],img.size[1])


# 将黑白图转化为0-1表示
def blackWrite(img):
    pixelShift = []
    for x in range(img.size[0]):
        rowList = []
        for y in range(img.size[1]):
            # 存在单一像素点不是纯黑纯白,取50为黑白分界线
            if img.getpixel((x,y)) < 50:
                rowList.append(0)
            else:
                rowList.append(1)
        pixelShift.append(rowList)
    return pixelShift


# 统计各气泡数字1
def statisticalNum(resultPixel):
    bubble = []     # 用于存放各气泡面积
    for x in range(len(resultPixel)):
        for y in range(len(resultPixel[0])):
            if resultPixel[x][y] == 1:
                resultPixel[x][y] = 0
                Coordinate = Queue()    # 存放该点四周为1的坐标点
                onlyCoordinate = []     # 防止重复的坐标点入队,并统计个数
                Coordinate.put([x,y])
                while not Coordinate.empty():
                    row = clo = 0
                    [row,clo] = Coordinate.get()
                    onlyCoordinate.append([row,clo])
                    # 查看左边坐标点
                    if clo > 0:
                        if (resultPixel[row][clo-1] == 1) and ([row,clo-1] not in onlyCoordinate):
                            Coordinate.put([row,clo-1])
                            resultPixel[row][clo-1] = 0
                    # 查看右边坐标点
                    if clo < (img.size[1]-1):
                        if (resultPixel[row][clo+1] == 1) and ([row,clo+1] not in onlyCoordinate):
                            Coordinate.put([row,clo+1])
                            resultPixel[row][clo+1] = 0
                    # 查看下边坐标点
                    if row < (img.size[0]-1):
                        if (resultPixel[row+1][clo] == 1) and ([row+1,clo] not in onlyCoordinate):
                            Coordinate.put([row+1,clo])
                            resultPixel[row+1][clo] = 0
                bubble.append(len(onlyCoordinate))
    return bubble


resultPixel = blackWrite(img)

bubble = statisticalNum(resultPixel);print('气泡个数为：',len(bubble))
bubble.sort()   #从小到大排序


